<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>

        <div class="filter-item">
            <label for="">班次名称：</label>
            <el-input
                v-model="searchForm.className"
                placeholder="请输入班次名称"
                style="width: 155px"
            />
        </div>
        <div class="filter-item">
            <label for="">班次类型：</label>
            <el-select
                v-model="searchForm.classType"
                placeholder="请选择班次类型"
                clearable
                style="width: 190px"
            >
                <el-option label="工作" value="1" />
                <el-option label="非工作" value="2" />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="search">查询</el-button>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="reset">重置</el-button>
        </div>
    </div>

    <div class="filter">
        <div class="filter-item">
            <el-button type="primary" @click="handleClick('add')"
                >新增班次</el-button
            >
        </div>
    </div>

    <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="depId" label="所属单位">
            <template #default="scope">
                {{ depNameTranslate(scope.row.depId) }}
            </template>
        </el-table-column>
        <el-table-column prop="className" label="班次名称" />
        <el-table-column prop="classShortName" label="班次简称" />
        <el-table-column prop="classType" label="班次类型">
            <template #default="scope">{{
                scope.row.classType == "1" ? "工作" : "非工作"
            }}</template>
        </el-table-column>
        <el-table-column prop="classStartTime" label="起止时间">
            <template #default="scope">
                {{ scope.row.classStartTime }} - {{ scope.row.classEndTime }}
            </template>
        </el-table-column>
        <el-table-column prop="duration" label="总时长（小时）" />
        <el-table-column prop="color" label="颜色" />
        <el-table-column fixed="right" label="操作" width="110">
            <template #default="scope">
                <el-button
                    text
                    type="primary"
                    size="small"
                    :disabled="scope.row.className == '休'"
                    @click="handleEdit(scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    text
                    type="danger"
                    size="small"
                    :disabled="scope.row.className == '休'"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                >
            </template>
        </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog
        v-model="addVisible"
        :title="addVisibleType == 'add' ? '新增' : '编辑'"
        width="680"
    >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item label="所属单位：" prop="depId" required>
                <el-select
                    v-model="ruleForm.depId"
                    class="m-2"
                    placeholder="请选择所属单位"
                    style="width: 190px"
                    :disabled="localTypeUnit != '1'"
                >
                    <el-option
                        v-for="item in newDepIdList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="班次类型：" prop="classType" required>
                <el-select
                    v-model="ruleForm.classType"
                    placeholder=""
                    style="width: 190px"
                >
                    <el-option label="工作" value="1" />
                    <el-option label="非工作" value="2" />
                </el-select>
            </el-form-item>

            <el-form-item label="班次名称：" prop="className" required>
                <el-input v-model="ruleForm.className" style="width: 190px" />
            </el-form-item>
            <el-form-item label="班次简称：" prop="classShortName" required>
                <el-input
                    v-model="ruleForm.classShortName"
                    style="width: 190px"
                />
            </el-form-item>
            <el-form-item
                label="颜色："
                prop="color"
                style="width: 100%"
                required
            >
                <el-color-picker
                    v-model="ruleForm.color"
                    :predefine="predefineColors"
                />
            </el-form-item>
            <el-form-item label="起止时间：" prop="classStartTime" required>
                <label style="margin-right: 10px">当天</label>

                <el-time-select
                    v-model="startTime"
                    style="width: 130px; margin-right: 10px"
                    start="00:00"
                    step="00:30"
                    end="23:59"
                    placeholder="开始时间"
                />
                <label style="margin-right: 10px">至</label>
                <el-select
                    v-model="dayValue"
                    placeholder=""
                    style="width: 120px; margin-right: 10px"
                >
                    <el-option label="当天" value="today" />
                    <el-option label="第二天" value="nextday" />
                </el-select>
                <el-time-select
                    v-model="endTime"
                    style="width: 130px; margin-right: 10px"
                    :min-time="endTimeMinTime"
                    :max-time="endTimeMaxTime"
                    start="00:00"
                    step="00:30"
                    end="23:59"
                    placeholder="结束时间"
                    :disabled="startTime == ''"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
// api
import schedulingHttp from "@/https/scheduling.js";
import { ElMessage, ElMessageBox } from "element-plus";
const depIdList = ref([
    { label: "全部", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const newDepIdList = ref([
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const depNameTranslate = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (item.value == depId) {
            depName = item.label;
        }
    });
    return depName;
};
let searchForm = reactive({
    depId: "",
    className: "",
    classType: "",
    isDelete: "0",
    pageNo: 1,
    pageSize: 10,
});
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;
let ruleForm = reactive({
    depId: localTypeUnit.value == "1" ? "" : localTypeUnit.value,
    classType: "",
    className: "",
    classShortName: "",
    color: "",
    classStartTime: "08:00",
    classEndTime: "",
});
const rules = reactive({
    depId: [
        {
            required: true,
            message: "请输入所属单位",
            trigger: "blur",
        },
    ],
    classType: [
        {
            required: true,
            message: "请输入班次类型",
            trigger: "blur",
        },
    ],
    className: [
        {
            required: true,
            message: "请输入班次",
            trigger: "blur",
        },
    ],
    classShortName: [
        {
            required: true,
            message: "请输入班次简称",
            trigger: "blur",
        },
    ],
    color: [
        {
            required: true,
            message: "请选择颜色",
            trigger: "blur",
        },
    ],
    classStartTime: [
        {
            required: false,
            message: "请输入开始时间",
            trigger: "blur",
        },
    ],
    classEndTime: [
        {
            required: false,
            message: "请输入结束时间",
            trigger: "blur",
        },
    ],
});
const ruleFormRef = ref();
const addVisibleType = ref("add");
const tableData = ref([]);
const addVisible = ref(false);
const dayValue = ref("today");
const startTime = ref("");
const endTime = ref("");
const endTimeMinTime = ref("");
const endTimeMaxTime = ref("");
const color = ref("ff4500");
const predefineColors = ref([
    "#ff4500",
    "#ff8c00",
    "#ffd700",
    "#90ee90",
    "#00ced1",
    "#1e90ff",
    "#c71585",
]);
watch(dayValue, (val) => {
    if (startTime.value !== "") {
        if (val == "nextday") {
            let timeArr = startTime.value.split(":");
            if (timeArr[0] == "23" && timeArr[1] == "30") {
                endTimeMaxTime.value = "23:30";
            } else {
                if (timeArr[1] == "30") {
                    endTimeMaxTime.value = parseInt(timeArr[0]) + 1 + ":00";
                } else {
                    endTimeMaxTime.value = parseInt(timeArr[0]) + ":30";
                }
            }
            endTimeMinTime.value = "";
        } else {
            endTimeMinTime.value = startTime.value;
            endTimeMaxTime.value = "";
        }
    }
});
watch(endTime, (val) => {
    ruleForm.classEndTime = val;
});
watch(startTime, (val) => {
    if (val == "") {
        endTime.value = "";
    }
    if (dayValue.value == "nextday") {
        let timeArr = val.split(":");
        if (timeArr[0] == "23" && timeArr[1] == "30") {
            endTimeMaxTime.value = "23:30";
        } else {
            if (timeArr[1] == "30") {
                endTimeMaxTime.value = parseInt(timeArr[0]) + 1 + ":00";
            } else {
                endTimeMaxTime.value = parseInt(timeArr[0]) + ":30";
            }
        }
        endTimeMinTime.value = "";
        if (minuteUnit(startTime.value) < minuteUnit(endTime.value)) {
            endTime.value = "";
        }
    } else {
        endTimeMinTime.value = startTime.value;
        endTimeMaxTime.value = "";
    }
    ruleForm.classStartTime = val;
});
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `是否删除该班次【班次名称：${row.className}】？`,
        "删除",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            schedulingHttp.workClassDelWorkClass({ id: row.id }).then((res) => {
                if (res.data.code == 200) {
                    ElMessage({
                        message: "删除成功",
                        type: "success",
                    });
                    search();
                } else {
                    ElMessage({
                        message: "删除失败！",
                        type: "error",
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除",
            });
        });
};

let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
// 查询班次信息;
const search = async () => {
    const res = await schedulingHttp.workClassQueryWorkClass(searchForm);
    if (res.data.code == 200) {
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
    }
};
const reset = () => {
    searchForm.depId = localTypeUnit.value;
    searchForm.className = "";
    searchForm.classType = "";
    search();
};
const handleClick = (type) => {
    if (type == "add") {
        addVisible.value = true;
        addVisibleType.value = "add";
        ruleForm.depId = localTypeUnit.value == "1" ? "" : localTypeUnit.value;
        ruleForm.classType = "";
        ruleForm.className = "";
        ruleForm.classShortName = "";
        ruleForm.color = "";
        ruleForm.classStartTime = "08:00";
        ruleForm.classEndTime = "";
        startTime.value = "";
        endTime.value = "";
        dayValue.value = "today";
    }
};
const handleEdit = (row) => {
    addVisible.value = true;
    addVisibleType.value = "edit";
    startTime.value = "";
    endTime.value = "";
    dayValue.value = "today";
    schedulingHttp.workClassQueryWorkTeamsDetail({ id: row.id }).then((res) => {
        if (res.data.code == 200) {
            ruleForm.id = res.data.data.id;
            ruleForm.depId = res.data.data.depId + "";
            ruleForm.classType = res.data.data.classType + "";
            ruleForm.className = res.data.data.className;
            ruleForm.classShortName = res.data.data.classShortName;
            ruleForm.color = res.data.data.color;
            startTime.value = fillZero(res.data.data.classStartTime).toString();

            if (
                minuteUnit(res.data.data.classStartTime) >=
                minuteUnit(res.data.data.classEndTime)
            ) {
                dayValue.value = "nextday";
            }
            endTime.value = fillZero(res.data.data.classEndTime).toString();
        } else {
            ElMessage({
                message: res.data.msg,
                type: "error",
            });
        }
    });
};
const fillZero = (time) => {
    if (time.length == 4) {
        return "0" + time;
    } else {
        return "" + time;
    }
};
const minuteUnit = (time) => {
    let timeList = time.split(":");
    let minut = timeList[1] == "00" ? 0 : 1;
    return parseInt(timeList[0]) * 2 + minut;
};
const cancel = () => {
    addVisible.value = false;
};
const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (addVisibleType.value == "add") {
                schedulingHttp.workClassAddWorkClass(ruleForm).then((res) => {
                    if (res.data.code == 200) {
                        addVisible.value = false;
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            } else if (addVisibleType.value == "edit") {
                schedulingHttp
                    .workClassUpdateWorkClass(ruleForm)
                    .then((res) => {
                        if (res.data.code == 200) {
                            addVisible.value = false;
                            search();
                        } else {
                            ElMessage({
                                message: res.data.msg,
                                type: "error",
                            });
                        }
                    });
            }
        } else {
            ElMessage({
                message: "提交错误",
                type: "danger",
            });
        }
    });
};
onMounted(() => {
    search();
});
</script>

<style scoped lang="less">
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}

.grid-content {
    line-height: 2;
}
.classTitle {
    margin: 20px 0;
    font-size: 16px;
    padding-left: 10px;
    border-left: 2px solid #409eff;
}
.el-transfer {
    display: flex;
    flex-direction: row;
    align-items: center;
}
:deep .el-transfer-panel {
    width: 300px;
}
:deep .el-transfer__buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
}
:deep .el-transfer__button:nth-child(2) {
    margin: 10px 0;
}
</style>